package com.ibm.rules.tree;

import java.math.BigInteger;
import java.util.Collection;
import java.util.Iterator;

import com.google.common.collect.Lists;
import com.ibm.cps.message.ParsedDataMessage;
import com.ibm.rules.Rule;
import com.ibm.rules.RulePartition;
import com.ibm.util.ErrorCode;
import com.ibm.util.exception.CPSException;

public class PartitionRuleTreeNode extends RuleTreeNode {
	@SuppressWarnings("rawtypes")
	RulePartition partition;

	@SuppressWarnings("rawtypes")
	public PartitionRuleTreeNode(RulePartition partition) {
		this.partition = partition;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public Collection<BigInteger> executeAllRules(Comparable[] fact)
			throws CPSException {
		RuleTreeNode node = partition.getRangeNodeByFact(fact);
		if (node == null)
			return Lists.newArrayList();
		return node.executeAllRules(fact);
	}
	
	@SuppressWarnings("rawtypes")
	@Override
	public Collection<BigInteger> executeAllRules(ParsedDataMessage msg)
			throws CPSException {
		RuleTreeNode node = partition.getRangeNodeByFact(msg);
		if (node == null)
			return Lists.newArrayList();
		return node.executeAllRules(msg);
	}

	@SuppressWarnings("rawtypes")
	public RulePartition getPartition() {
		return partition;
	}

	@SuppressWarnings("unchecked")
	public void mergeNode(PartitionRuleTreeNode node) {
		partition.mergePartiton(node.getPartition());
	}

	@Override
	@SuppressWarnings("unchecked")
	public boolean addIncrementalRule(Rule rule) throws CPSException {
		Collection<RuleTreeNode> nodes = partition.getRangeNodesByRule(rule);
		Iterator<RuleTreeNode> iter = nodes.iterator();
		boolean ret = true;
		while (iter.hasNext()) {
			if (!iter.next().addIncrementalRule(rule))
				ret = false;
		}
		return ret;
	}

	@Override
	public void deleteRuleByName(String ruleName) throws CPSException {
		throw new CPSException(ErrorCode.NO_IMPLEMENTATION_CODE,
				"do not support delete rule");
	}

}
